<?php
/*
 * --------------------------------------------------------------------
 * 小微OA系统 - 让工作更轻松快乐 Copyright (c) 2013
 * http://www.smeoa.com All rights reserved.
 * Author: jinzhu.yin<smeoa@qq.com>
 * Support: https://git.oschina.net/smeoa/xiaowei --------------------------------------------------------------------
 */
use sef\controller;
use sef\model;

class crm_company_controller extends base_controller {
	protected $app_type = "common";
	protected $auth_map = array('read' => 'add,edit,save', 'admin' => 'import_data,del,field_manage,export');

	function _search_filter(&$where) {
		$where[] = array('is_del', 'eq', '0');
		$keyword = request('keyword');
		if (!empty($keyword)) {
			$where[] = array('name', 'like', $keyword);
		}
	}

	public function index() {
		$model = model('crm_company');
		$where = $this -> _search($model);
		if (method_exists($this, '_search_filter')) {
			$this -> _search_filter($where);
		}
		$auth = $this -> auth;
		$this -> assign('auth', $auth);
		if ($auth -> admin) {

		} elseif ($auth -> write) {
			$where_user[] = array('dept_id', 'eq', get_dept_id());
			$user_list = model('user') -> where($where_user) -> get_field('id', true);
			$where[] = array('user_id', 'in', $user_list);
		} elseif ($auth -> read) {
			$where[] = array('user_id', 'eq', get_user_id());
		} else {
			$where[] = array('string', 'eq', '1=2');
		}

		if (request('mode') == 'export') {
			$this -> _index_export($model, $where);
		} else {
			$this -> _list($model, $where);
		}
		$this -> display();
	}

	// 添加公司
	public function add() {

		$model_flow_field = model('udf_field');
		$field_list = $model_flow_field -> get_field_list(0);
		$this -> assign('field_list', $field_list);

		$this -> display();
	}

	public function edit($id) {
		$model = model('crm_company');
		$vo = $model -> find($id);
		if (empty($vo)) {
			$this -> error("系统错误");
		}
		$field_list = model("udf_field") -> get_data_list(0, $vo['udf_data']);
		$this -> assign("field_list", $field_list);

		$this -> assign("vo", $vo);
		$this -> display();
	}

	/** 插入新新数据  **/
	protected function _insert($name = APP_NAME) {
		$model = model($name);
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		$model -> udf_data = model('udf_field') -> get_field_data();
		$model -> letter = get_letter($model -> name);
		$list = $model -> add();
		if ($list !== false) {
			$this -> success('新增成功!');
		} else {
			$this -> error('新增失败!');
		}
	}

	/* 更新数据  */
	protected function _update($name = APP_NAME) {
		$model = model($name);
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		$model -> udf_data = model('udf_field') -> get_field_data();
		$list = $model -> save();
		if (false !== $list) {
			$this -> success('编辑成功!', get_return_url());
		} else {
			$this -> error('编辑失败!');
		}
	}

	public function import_data() {
		$opmode = request('opmode');
		if ($opmode == "import") {
			$import_user = array();
			$file = model('file');
			$info = $file -> upload($_FILES['uploadfile']);
			
			if (!$info) {
				$this -> error('上传错误');
			} else {
				//取得成功上传的文件信息
				vendor();
				$root_path = config('root_path');
				$root_path = 'uploads';
				$file_path = $root_path . DS . $info['save_path'] . DS . $info['save_name'];

				$excel = \PHPExcel_IOFactory::load($file_path);
				//$objPHPExcel = \PHPExcel_IOFactory::load('Uploads/Download/Org/2014-12/547e87ac4b0bf.xls');
				$sheet_data = $excel -> getActiveSheet() -> toArray(null, true, true, true);

				$model = model('crm_company');
				foreach ($sheet_data[1] as $v) {
					$udf_data_key[] = $v;
				}
				for ($i = 1; $i <= count($sheet_data); $i++) {
					foreach ($sheet_data[$i] as $v) {
						$udf[$i][] = $v;
					}
				}
				for ($i = 2; $i <= count($udf); $i++) {
					$data['name'] = $udf[$i][0];
					$data['user_id'] = get_user_id();
					$data['user_name'] = get_user_name();
					$data['create_time'] = time();
					$data['website'] = $udf[$i][1];
					$data['contacts'] = $udf[$i][2];
					$data['address'] = $udf[$i][3];
					$data['remark'] = $udf[$i][4];
					for ($z = 5; $z < count($udf_data_key); $z++) {
						$where[] = array('name', 'eq', $udf_data_key[$z]);
						$where[] = array('controller', 'eq', 'crm_company');
						$udffield = model('udf_field') -> where($where) -> find();
						$udf_data[$udffield['id']] = $udf[$i][$z];
					}
					$data['udf_data'] = json_encode($udf_data);
					$model -> add($data);
				}
				$this -> assign('jumpUrl', get_return_url());
				$this -> success('导入成功！');
			}
		} else {
			$this -> display();
		}
	}

	function _index_export($model, $map) {
		$list = $model -> where($map) -> select();
		$r = $model -> where($map) -> count();
		$model_flow_field = model("UdfField");

		//导入thinkphp第三方类库
		Vendor('Excel.PHPExcel');
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel -> getProperties() -> setCreator("小微OA") -> setLastModifiedBy("小微OA") -> setTitle("Office 2007 XLSX Test Document") -> setSubject("Office 2007 XLSX Test Document") -> setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") -> setKeywords("office 2007 openxml php") -> setCategory("Test result file");
		$i = 1;

		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", "公司名称");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("B$i", "创建人");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("C$i", "创建时间");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("D$i", "网址");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("E$i", "地址");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("F$i", "联系人");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("G$i", "备注");

		$udf_list = model('UdfField') -> get_field_list(0, 'CrmCompany');
		foreach ($udf_list as $val) {
			$k++;
			$location = get_cell_location('H', $i, $k);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue($location, $val['name']);
		}
		foreach ($list as $val) {
			$i++;

			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", $val['name']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("B$i", $val['user_name']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("C$i", to_date($val['create_time']));
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("D$i", $val['website']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("E$i", $val['address']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("F$i", $val['contacts']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("G$i", strip_tags($val['remark']));

			$field_list = $model_flow_field -> get_data_list(0, $val["udf_data"]);
			$k = 'H';
			if (!empty($field_list)) {
				foreach ($field_list as $field) {
					$k++;
					$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("$k$i", $field['val']);
				}
			}
		}
		$objPHPExcel -> getActiveSheet() -> setTitle('公司信息');

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel -> setActiveSheetIndex(0);
		$file_name = "公司信息.xlsx";
		// Redirect output to a client’s web browser (Excel2007)
		header("Content-Type: application/force-download");
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header("Content-Disposition:attachment;filename =" . str_ireplace('+', '%20', URLEncode($file_name)));
		header('Cache-Control: max-age=0');

		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		//readfile($filename);
		$objWriter -> save('php://output');
		exit ;
	}

	function export() {
		$model = M('CrmCompany');
		$list = $model -> where($_SESSION['report']) -> select();
		$title = array('公司名称', '创建人', '创建时间', '网址', '地址', '联系人');
		$json_data = $model -> field('udf_data') -> select();
		$UdfField = M('UdfField');
		foreach ($json_data as $v) {
			foreach (json_decode($v['udf_data'],true) as $k => $v) {
				$where['id'] = $k;
				$name = $UdfField -> where($where) -> find();
				$title[] = $name['name'];
			}
		}
		$title = array_unique($title);
		$this -> exportexcel($list, $title, 'report');
	}

	function exportexcel($list = array(), $title = array(), $filename = 'report') {
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:attachment;filename=" . $filename . ".xls");
		header("Pragma: no-cache");
		header("Expires: 0");
		//导出xls 开始
		if (!empty($title)) {
			foreach ($title as $k => $v) {
				$title[$k] = iconv("UTF-8", "GB2312", $v);
			}
			$title = implode("\t", $title);
			echo "$title\n";
		}
		if (!empty($list)) {
			foreach ($list as $key => $val) {
				$data[$key]["name"] = iconv("UTF-8", "gb2312", $val['name']);
				$data[$key]["user_name"] = iconv("UTF-8", "gb2312", $val['user_name']);
				$data[$key]['create_time'] = iconv("UTF-8", "gb2312", date('Y-m-d', $val['create_time']));
				$data[$key]['website'] = iconv("UTF-8", "gb2312", $val['website']);
				$data[$key]['address'] = iconv("UTF-8", "gb2312", $val['address']);
				$data[$key]['contacts'] = iconv("UTF-8", "gb2312", $val['contacts']);

				foreach (json_decode($val['udf_data'],true) as $k => $v) {
					$data[$key][$k] = iconv("UTF-8", "gb2312", $v);
				}
				$data[$key] = implode("\t", $data[$key]);

			}

			echo implode("\n", $data);
		}
	}

	// 删除公司
	public function del($id) {
		$this -> _del($id);
	}

	function field_manage() {
		$this -> assign("folder_name", "公司自定义字段管理");
		$this -> _field_manage(0);
	}

	public function upload() {
		$this -> _upload();
	}

	function down($sid) {
		$this -> _down($sid);
	}

}
